﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Fasterflect;
using LL.Data;

namespace LL.Data
{
    public static class DbSessionFactory
    {
        public static IDbSessionFactory factory = null;

        static DbSessionFactory()
        {
            factory = CreateInstance();
        }

        public static IDbSession NewSession(bool keepAlive = false)
        {
            return factory.NewSession(keepAlive);
        }

        public static IDbSession NewSession(string connectionName, bool keepAlive = false)
        {
            return factory.NewSession(connectionName, keepAlive);
        }

        static IDbSessionFactory CreateInstance()
        {

            //LL.Data.FluentData.dll可以看做是DAL或者是一个适配器（将FluentData适配为LL.Data数据接口）
            //LL.Data.FluentData.dll中的成员实现了LL.Data的接口
            //LL.Data.FluentData.dll可以换成LL.Data.LL.dll而无需改动上层代码
            //if (!System.IO.File.Exists("LL.Data.FluentData.dll"))
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                ConfigurationManager.AppSettings["DataProviderPath"]);
            if (!System.IO.File.Exists(filePath))
                throw new FileNotFoundException(filePath);

            var ass = AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(filePath));
            return Activator.CreateInstance(ass.TypesImplementing<IDbSessionFactory>().First()) as IDbSessionFactory;
        }
    }
}
